﻿import java.sql.* ;
import java.util.Vector;


public class LoadData
{
	//Set Dirver Address
	String Jdbc_Driver = "org.sqlite.JDBC";
	//Set Database Address
	String DB_Url = "jdbc:sqlite:Food_Database";
	Connection con = null;
	Statement stmt = null;
	public class Food
	{
		public int    Kind  ;	//種類
		public int    ID   ;	//其ID號碼 0,1,2,...
		public String Name  ;	//名字
		public double Kcal ;	//熱量
		public Food( int id , int kind , String name , double cal )
    	{
			this.ID   = id ;
			this.Kind = kind ;
			this.Name = name ;
			this.Kcal = cal ;
		}
	}
	public Food NowFood ; 
	//串成一串食物
	public Vector <Food> AllKindFood = new Vector <Food> ( ) ;
	LoadData( int Kind , String Test )
	{
		try
		{
			//Load Driver
			Class.forName(Jdbc_Driver);
	
			System.out.println("Connecting to database ...");
			//Establish Connetion with Database
			con = DriverManager.getConnection(DB_Url);
			System.out.println("Connected to database successfully");
	
			/*
			InputStream is = System.in;
			Scanner scan = new Scanner(is);
			System.out.println("Enter the name of loading table : ");
			String Table_Name = scan.next();
			*/
			
			String Table_Name = Test ;
			
			System.out.println("Loading data ...");
			stmt = con.createStatement();
	
			//Select Which information you want to get from which table
			String Load_Data = "SELECT id,name,calorie FROM " + Table_Name;
			ResultSet rs = stmt.executeQuery(Load_Data);
			double Tc = 0 ;
			double Mc = 0 ;
			while(rs.next())
			{
				int id = rs.getInt("id");
				String name = rs.getString("name");
				int calorie = rs.getInt("calorie");
				Tc += calorie ;
				//Food
				
				AllKindFood.add( new Food( (int) Mc , Kind , name , (double)calorie ) ) ;
				//NowFood.Mount++ ;
				Mc += 1 ;
				System.out.println("ID: " + id + " Name: " + name + " Calorie: " + calorie);
			}
			rs.close( );
			Tc = Tc / Mc ;
			//AllKindFood.add( NowFood ) ;
			System.out.println( Load_Data + "Avg:" + Tc ) ;
		}
		catch(SQLException se)
		{
			se.printStackTrace();
		}
		catch(Exception e)
		{
			e.printStackTrace();
		}
		finally
		{
			try
			{
				if(stmt != null)
					con.close();
			}
			catch(SQLException se)
			{
			}
	
			try
			{
				if(con != null)
					con.close();
			}
			catch(SQLException se)
			{
				se.printStackTrace();
			}
		}
		System.out.println("Load Done!!");
	}
}
